
#include "socket.hpp"
#include "ThreadPool.hpp"
#include <iostream>
#include <functional>
#include <string>

using task_t = std::function<void()>;
using callback_t = std::function<std::string(std::string &)>;

class HttpServer
{

    void Route(NetWork::Socket *sock)
    {
        // 获取字节流数据
        std::string recv_package;
        std::string send_package;
        int recv_size = 1024;

        // 服务器获取客户端传来的字节流报文
        sock->Recv(&recv_package, recv_size);

        send_package = _handler(recv_package); // 外部调用
        std::cout << send_package.c_str() << std::endl;
        sock->Send(send_package);
        // 结束当前短连接路由
        std::cout << "client quit......" << std::endl;
        sock->CloseSockFd();
        delete sock;
    }

public:
    HttpServer(uint16_t port, callback_t func) : _port(port), _handler(func)
    {
        _listen_socket = new NetWork::TcpSocket();
        _listen_socket->BuildListenSocketMethod(port);
    }

    ~HttpServer()
    {
        delete _listen_socket;
    }
    void Init()
    {
        // 初始化线程池
        zhong::ThreadPool<task_t>::GetInstance()->Start();
    }
    void Start()
    {
        while (1)
        {
            // 服务器从网络获取client信息
            // struct sockaddr_in peer;
            uint16_t peer_port;
            std::string peer_ip;
            std::cout << "listen fd = " << _listen_socket->GetSockFd() << std::endl;
            NetWork::Socket *new_socket = _listen_socket->AcceptConnection(&peer_ip, &peer_port);
            if (new_socket == nullptr)
                continue;
            std::cout << "Accept connection from fd = " << new_socket->GetSockFd() << " success, client info[" << peer_ip << ":" << peer_port << "]" << std::endl;

            // 多线程处理链接
            // task_t t = std::bind(HttpServer::Route, this, new RouteData(this, new_socket));    传入RouteData相关代码
            task_t t = std::bind(&HttpServer::Route, this, new_socket);
            zhong::ThreadPool<task_t>::GetInstance()->Push(t);
            // new_socket->CloseSockFd();
        }
    }

private:
    NetWork::Socket *_listen_socket;
    uint16_t _port;
    callback_t _handler; // 可以实现业务版本 std::unordered_map<std::string, callback_t> _func_map;
};
